# encoding=utf-8
# author:梁子龙
import random

from flask_restful import Resource
from flask import current_app, request, g

from asys_main.resource.user.const import SMS_CODE_EXPIRES
from comment.modules.user import User
from sqlalchemy import and_, or_, func
from flask_sqlalchemy import SQLAlchemy

# func.count()

from comment.utils.blog_redis import redis_client
from flask_restful.reqparse import RequestParser
from comment.modules import db
from comment.utils.tokens import generate_tokens, verify_tokens
from comment.utils.decorators import login_required
from asys_main.resource.user.serializer import UserInfoSerializer, OrderListSerializer, RoleInfoSerializer, \
    PermissionSerializer, AllUserInfoSerializer, ProjectSerializer


class RegisterUser(Resource):
    """
    用户的注册
    """

    def get(self):
        return {"msg": "welcome asys company", "data": {"info": "please register"}, "code": "200"}

    def post(self):
        rp = RequestParser()
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        args = rp.parse_args()
        username = args.username
        password = args.password

        u = User.query.filter(User.username == username).first()
        if u:  # 用户名存在
            return {'message': '用户名重复', 'code': 20001}
        u = User(username=username, pwd=password)
        try:  # 需要用到数据库事务处理
            db.session.add(u)
            db.session.commit()
            return {"msg": "注册成功"}, 200
        except Exception as ex:
            current_app.logger.error(ex)
            db.session.rollback()
            return {'message': '用户注册时，插入数据库失败', 'code': 20001}, 400


class UserCode(Resource):
    def get(self):
        # mobile = request.args.get("phone").strip()
        mobile = 13930046925
        code = random.randint(111111, 999999)
        # redis_client.setex(f"blog:{mobile}", SMS_CODE_EXPIRES, code)
        redis_client.setex("blog:{}".format(mobile), SMS_CODE_EXPIRES, code)

        return {"msg": "welcome asys company", "data": {"info": "please register"}, "code": "200"}

    def post(self):
        rp = RequestParser()
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        args = rp.parse_args()
        username = args.username
        password = args.password

        u = User.query.filter(User.username == username).first()
        if u:  # 用户名存在
            return {'message': '用户名重复', 'code': 20001}
        u = User(username=username, pwd=password)
        try:  # 需要用到数据库事务处理
            db.session.add(u)
            db.session.commit()
            return {"msg": "注册成功"}, 200
        except Exception as ex:
            current_app.logger.error(ex)
            db.session.rollback()
            return {'message': '用户注册时，插入数据库失败', 'code': 20001}, 400


class Login(Resource):
    """
    登录
    """

    def get(self):
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        res = UserInfoSerializer(user).to_dict()

        return {"msg": "ok", "data": res}

    def post(self):
        rp = RequestParser()
        # rp.add_argument('employeeId', required=True)
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        args = rp.parse_args()
        username = args.username  # 用户------>id
        password = args.password  # 密码
        user = User.query.filter(User.username == username).first()
        if user:
            # 验证密码是否
            if user.check_password(password):
                # 用户登录成功，之后生产一个token，以便于后面去认真token
                token = generate_tokens(user.id)
                if verify_tokens(token):
                    role = {"1": "管理员", "2": "普通用户"}
                    position = role.get(str(user.role))
                    info = {"username": user.username, "role": position, "msg": "登录成功", "code": "200", 'token': token}
                    return info

                    return {"msg": "login", "code": "200", 'token': token}, 200
                # return {'message': '登陆成功。', 'code': 20001}, 200
            return {'message': '用户名或者密码错误。'}, 401
        return {'message': '用户不存在', 'code': 40001}

    def put(self):
        rp = RequestParser()
        rp.add_argument('old_password', required=True)
        rp.add_argument('new_password', required=True)
        args = rp.parse_args()
        old_password = args.old_password  # 密码
        new_password = args.new_password  # 用户
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        if user:
            if user.check_password(old_password):
                user.pwd = new_password
                db.session.commit()
                return {'msg': '密码修改成功。', 'code': 20001}, 200
            return {'msg': '原密码不对', 'code': 20001}, 401
        return {'msg': '用户不存在。', 'code': 20001}, 401


class PersonInfo(Resource):
    decorators = [login_required]

    @staticmethod
    def post():
        rp = RequestParser()
        rp.add_argument('email', required=True)
        rp.add_argument('desc', required=True)
        rp.add_argument('is_active', required=True)
        args = rp.parse_args()
        email = args.email
        desc = args.desc
        is_active = args.is_active
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        if user:
            user.email = email
            user.desc = desc
            user.is_active = is_active
            s = request
            print(request.remote_addr)  # 127.0.0.1
            print(request.url)  # http://127.0.0.1:5000/api/userinfo
            print(request.path)  # /api/userinfo
            db.session.commit()
            return {"msg": "个人信息修改完毕", "code": "20006"}

        return {'message': '用户不存在', 'code': 40001}


class Password(Resource):
    decorators = [login_required]

    def put(self):
        rp = RequestParser()
        rp.add_argument('passwordOld', required=True)
        rp.add_argument('passwordNew', required=True)
        args = rp.parse_args()
        old_password = args.passwordOld  # 密码
        new_password = args.passwordNew  # 用户
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        if user:
            if user.check_password(old_password):
                user.pwd = new_password
                db.session.commit()
                return {'msg': '密码修改成功'}, 200
            return {'msg': '原密码不对', }, 401
        return {'msg': '用户不存在。', 'code': 20001}, 401


class CurrentUser(Resource):
    method_decorators = [login_required]

    def get(self):
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        res = UserInfoSerializer(user).to_dict()

        return {"msg": "请求成功", "data": res, }, 200


class AllUser(Resource):
    method_decorators = [login_required]

    def get(self):
        user = User.query.all()
        res = AllUserInfoSerializer(user).to_dict()

        return {"msg": "请求成功", "data": res}, 200


class LoginOut(Resource):
    """
    退出登录
    """
    # 使用了登录拦截的装饰器
    method_decorators = [login_required]

    def post(self):
        if g.user_id:
            g.user_id = None
        return {'msg': '成功退出登录'}
